<?php
namespace App\Services;

use App\Models\Child;
use App\Models\User;
use Zjwshisb\App;

class FaceService {

    protected $app;

    public function __construct()
    {
        $this->app = new App(config("face"));
    }

    public function getPerson($personId) {
        $res = $this->app->manager->getPerson($personId);
        if($res['code'] !== 0) {
            return false;
        }
        return $res['data'];

    }

    public function addFaceByUrl($personId,$url){
        return $this->app->manager->addFaceUrl($personId, [$url]);
    }

    public function deletePerson($personId){
        return $this->app->manager->delPerson($personId);
    }


    public function createPerson($personId, $faceUrl, $groupIds = ['teacher']){
        return $this->app->manager->newPersonUrl($groupIds,$personId, $faceUrl);
    }

    public function createPersonByBinary($personId, $images , $groupIds = ['teacher']){
        return $this->app->manager->newPersonImage($groupIds,$personId, $images);
    }


    public function identifyPerson($img, $group = "teacher"){
        try{
            $res = $this->app->identity->identifyByBase64($img , $group);
            if($res['code'] !== 0) {
                throw new \Exception($res['message']);
            }
            \Log::info(json_encode($res));
            if(isset($res['data']['candidates'][0])){
                $person = $res['data']['candidates'][0];
                if($person["confidence"] >= 75) {
                    $id = $person['person_id'];
                    if (substr($id, 0,7) === 'student') {
                        $id = substr($id , 8);
                        return Child::query()->find($id);
                    } else {
                        return User::query()->find($id);;
                    }

                }
            }
            return false;
        }catch (\Exception $e){
            \Log::info($e->getMessage());
            return false;
        }


    }
}
